// 通用表单验证工具
const FormValidation = {
    // 验证规则
    rules: {
        required: (value) => value && value.trim() !== '',
        email: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
        phone: (value) => /^1[3-9]\d{9}$/.test(value),
        minLength: (min) => (value) => value && value.length >= min,
        maxLength: (max) => (value) => value && value.length <= max,
        number: (value) => !isNaN(value) && value !== '',
        positiveNumber: (value) => !isNaN(value) && parseFloat(value) > 0,
        range: (min, max) => (value) => {
            const num = parseFloat(value);
            return !isNaN(num) && num >= min && num <= max;
        }
    },

    // 验证消息
    messages: {
        required: '此字段为必填项',
        email: '请输入有效的邮箱地址',
        phone: '请输入有效的手机号',
        minLength: (min) => `至少需要${min}个字符`,
        maxLength: (max) => `最多${max}个字符`,
        number: '请输入有效数字',
        positiveNumber: '请输入大于0的数字',
        range: (min, max) => `请输入${min}-${max}之间的数字`
    },

    // 验证单个字段
    validateField(value, rules) {
        const errors = [];
        
        for (const rule of rules) {
            if (typeof rule === 'string') {
                if (!this.rules[rule](value)) {
                    errors.push(this.messages[rule]);
                }
            } else if (typeof rule === 'object') {
                const { type, params, message } = rule;
                if (!this.rules[type](...params)(value)) {
                    errors.push(message || this.messages[type](...params));
                }
            }
        }
        
        return errors;
    },

    // 验证整个表单
    validateForm(formData, schema) {
        const errors = {};
        
        for (const [field, rules] of Object.entries(schema)) {
            const fieldErrors = this.validateField(formData[field], rules);
            if (fieldErrors.length > 0) {
                errors[field] = fieldErrors[0]; // 只显示第一个错误
            }
        }
        
        return {
            isValid: Object.keys(errors).length === 0,
            errors
        };
    },

    // 预定义验证模式
    schemas: {
        user: {
            realName: ['required'],
            phone: ['required', 'phone'],
            email: ['required', 'email'],
            username: ['required', { type: 'minLength', params: [3], message: '用户名至少3个字符' }]
        },
        subject: {
            name: ['required'],
            code: ['required', { type: 'minLength', params: [2], message: '学科代码至少2个字符' }],
            description: ['required'],
            credit: ['required', 'positiveNumber', { type: 'range', params: [1, 10], message: '学分必须在1-10之间' }]
        },
        score: {
            studentId: ['required'],
            subjectId: ['required'],
            score: ['required', { type: 'range', params: [0, 100], message: '成绩必须在0-100之间' }],
            semester: ['required']
        }
    }
};

// 注册到全局作用域
window.FormValidation = FormValidation;
